package com.lej.upgrade

import android.annotation.SuppressLint
import android.view.View
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.isVisible
import androidx.fragment.app.FragmentActivity
import com.lej.core.base.app
import com.lej.core.common.LogTags
import com.lej.core.utils.extention.*
import com.lej.dataservice.club.bean.upgrade.UpgradeInfo
import com.lej.dataservice.club.http.baseApiService
import com.lej.dataservice.club.http.checkData
import com.lej.dataservice.club.http.rx.CustomNetworkException
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.CenterPopupView
import com.lxj.xpopup.util.XPopupUtils
import com.qmuiteam.qmui.kotlin.onClick
import com.qmuiteam.qmui.widget.QMUIProgressBar
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch

/**[getVersion] 返回空字符串或者null的时候代表不用更新*/
@SuppressLint("SetTextI18n")
fun checkDownload(
    activity: FragmentActivity,
    needToast: Boolean = false,
    getVersion: suspend () -> UpgradeInfo?,
    resultListener: () -> Unit = {}
) {
    "开始检查更新".logI(LogTags.upgrade)
    MainScope().launch {
        val info = getVersion()
        if (info == null || info.url.isNullOrEmpty()) {
            if (needToast) "已经是最新版本".toast()
            "没检查到更新".logI(LogTags.upgrade)
            resultListener()
            return@launch
        }
        "检查到更新".logI(LogTags.upgrade)
        XPopup.Builder(activity)
            .dismissOnBackPressed(false)
            .hasStatusBar(false)
            .hasBlurBg(true)
            .dismissOnTouchOutside(false)
            .asCustom(object : CenterPopupView(activity) {
                override fun getImplLayoutId() = R.layout.dialog_version_info
                override fun initPopupContent() {
                    super.initPopupContent()
                    findViewById<TextView>(R.id.tv_message)?.text = info.content
                    findViewById<TextView>(R.id.tv_title)?.text = "检查到${info.version}版本更新"
                    findViewById<View>(R.id.btn_cancel)?.apply {
                        isVisible = !info.isForce()
                        onClick {
                            dismiss()
                            resultListener()
                        }
                    }
                    findViewById<TextView>(R.id.btn_update)?.onClick {
                        dismiss()
                        upgradeDialog(activity, info)
                    }
                }

                override fun getMaxWidth() = XPopupUtils.getWindowWidth(context)
            })
            .show()
    }
}

private var taskId: Long = 0

private fun upgradeDialog(activity: FragmentActivity, info: UpgradeInfo) {
    XPopup.Builder(activity)
        .dismissOnBackPressed(!info.isForce())
        .hasStatusBar(false)
        .hasBlurBg(true)
        .dismissOnTouchOutside(false)
        .asCustom(object : CenterPopupView(activity) {
            private var btnUpdate: TextView? = null

            override fun getImplLayoutId() = R.layout.dialog_upgrade

            @SuppressLint("SetTextI18n")
            override fun initPopupContent() {
                super.initPopupContent()
                val progressBar = findViewById<QMUIProgressBar>(R.id.QMUIProgressBar)
                val tvMsg = findViewById<TextView>(R.id.tv_msg)
                findViewById<TextView>(R.id.tv_title).text = info.content ?: ""
                findViewById<View>(R.id.btn_cancel)?.apply {
                    isVisible = !info.isForce()
                    onClick {
                        DownloadHelper.cancel(taskId)
                        dismiss()
                    }
                }
                btnUpdate = findViewById(R.id.btn_update)
                btnUpdate?.isVisible = false
                btnUpdate?.onClick {
                    activity.checkPermissionAndInstall(info.version_code)
                }
                val apkPath = activity.cacheDir.path + "/${info.version_code}.apk"
                DownloadHelper.init(activity)
                taskId = DownloadHelper.start(info.url, apkPath) { status, process ->
                    when (status) {
                        DownloadHelper.DOWNLOAD_LOADING -> {
                            progressBar?.progress = process
                            tvMsg?.text = "下载中:${process}%"
                        }
                        DownloadHelper.DOWNLOAD_SUC -> {
                            progressBar?.progress = process
                            tvMsg?.text = "下载完成:${process}%"
                            btnUpdate?.isVisible = true
                            activity.checkPermissionAndInstall(info.version_code)
                        }
                        DownloadHelper.DOWNLOAD_FAIL -> "下载失败".toast()
                    }
                }
            }
        })
        .show()
}

private val getUrl: suspend () -> UpgradeInfo? = {
    runCatching {
        val info = baseApiService.getVersion(app.versionCode).checkData()
        info.toString().logI(LogTags.upgrade)
        ///如果已经是最新版本，返回null代表不用更新
        hasCheckUpgrade = true
        if (info.isNew()) null else info
    }.onFailure {
        "获取最新版本失败".logI(LogTags.upgrade)
        it.message?.logI(LogTags.upgrade)
        (it as? CustomNetworkException)?.code.toString().logI(LogTags.upgrade)
        it.logE(LogTags.upgrade)
    }.getOrNull()
}

/**[limitTimes] 限制一个生命周期就检查一次*/
fun checkUpgrade(activity: AppCompatActivity, limitTimes: Boolean = true,resultListener:() -> Unit = {}) {
    if (!limitTimes || !hasCheckUpgrade)
        checkDownload(activity, needToast = !limitTimes, getVersion = getUrl,resultListener)
}

private var hasCheckUpgrade: Boolean = false